package com.zero.zeroframe.ktx

import android.text.InputFilter
import android.widget.EditText
import com.zero.zeroframe.utils.MoneyInputFilter

/**
 * EditText相关扩展方法
 *
 * @author Qu Yunshuo
 * @since 2020/9/17
 */

/**
 * 过滤掉空格和回车
 */
fun EditText.filterBlankAndCarriageReturn() {
    val filterList = mutableListOf<InputFilter>()
    filterList.addAll(filters)
    filterList.add(InputFilter { source, _, _, _, _, _ -> if (source == " " || source == "\n") "" else null })
    filters = filterList.toTypedArray()
}

/**
 * 金额输入限制
 */
fun EditText.moneyInputFilter() {
    filters = arrayOf(MoneyInputFilter())
}

fun EditText.lastSelection() {
    setSelection(text.length)
}

/**
 * 输出double值
 */
fun EditText.textToDouble():Double {
    val str = text.toString()
    if (str.isEmpty()){
        return 0.0
    }
    return str.toDouble()
}

/**
 * 输出int值
 */
fun EditText.textToInt():Int {
    val str = text.toString()
    if (str.isEmpty()){
        return 0
    }
    return str.toInt()
}